﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone

using BlazorAdmin.Models;
using BlazorAdmin.Interface;
using PetaPoco;
using System;
using System.Linq;
using System.Collections.Generic;
using BlazorAdmin.Extensions;
using BlazorAdmin.Services.DbService;

namespace BlazorAdmin.Services
{
    public class TraceService : BaMgmtDbService, ITrace
    {
        public TraceService(IPetaPoco db) : base(db) { }

        public void Log(Trace trace)
        {
            trace.Browser = Utils.GetClientBrowser(trace.UserAgent);
            trace.OS = Utils.GetClientOS(trace.UserAgent);
            trace.LogTime = DateTime.Now;

            Insert(trace);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchText"></param>
        /// <param name="filter"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageItems"></param>
        /// <param name="sortList"></param>
        /// <returns></returns>
        public (IEnumerable<Trace> Items, int ItemsCount) GetAll(string searchText, TraceFilter filter, int pageIndex, int pageItems, List<string> sortList)
        {
            var sql = new Sql();
            if (!string.IsNullOrEmpty(searchText))
            {
                sql.Where("UserName LIKE @0 OR IP LIKE @0 OR RequestUrl LIKE @0", $"%{searchText}%");
            }

            if (!string.IsNullOrEmpty(filter.UserName))
            {
                sql.Where("UserName LIKE @0", $"%{filter.UserName}%");
            }

            if (!string.IsNullOrEmpty(filter.Ip))
            {
                sql.Where("IP LIKE @0", $"%{filter.Ip}%");
            }

            if (!string.IsNullOrEmpty(filter.RequestUrl))
            {
                sql.Where("ErrorPage LIKE @0", $"%{filter.RequestUrl}%");
            }

            sql.Where("LogTime >= @0 AND LogTime <= @1", filter.Start, filter.End);

            if (sortList.Any())
            {
                sql.OrderBy(string.Join(", ", sortList));
            }
            else
            {
                sql.OrderBy("Logtime DESC");
            }

            using var db = Create();
            var data = db.Page<Trace>(pageIndex, pageItems, sql);
            return (data.Items, Convert.ToInt32(data.TotalItems));
        }
    }
}